<!DOCTYPE html>
<html lang="en">

<head>
    <meta charset="UTF-8">
    <meta http-equiv="X-UA-Compatible" content="IE=edge">
    <meta name="viewport" content="width=device-width, initial-scale=1.0">
    <title>Document</title>
</head>
<style>
    * {
        margin: 0;
        padding: 0;
    }

    .wrap {
        width: 800px;
        height: 400px;
        margin: 0 auto;
    }

    table {
        margin: 20px auto;
    }
</style>

<body>
    <div class="wrap">
        <table cellspacing="20">
            <tr>
                <th><input type="checkbox" value="全选" id="all" /></th>
                <th>产品</th>
                <th>价钱</th>
            </tr>
            <tr>
                <td><input type="checkbox" class="check" /></td>
                <td>iphone</td>
                <td>5000</td>
            </tr>
            <tr>
                <td><input type="checkbox" class="check" /></td>
                <td>iwatch</td>
                <td>2000</td>
            </tr>
            <tr>
                <td><input type="checkbox" class="check" /></td>
                <td>ipad</td>
                <td>3000</td>
            </tr>
        </table>
        <button class="inverse">反选</button>
    </div>
    <script>
        // 先获取准备使用的节点
        var checkboxAll = document.querySelectorAll('.check');
        var checkAllBtn = document.querySelector('#all');
        var reverseBtn = document.querySelector('.inverse');

        // 全选按钮
        checkAllBtn.onclick = function () {
            var status = checkAllBtn.checked;
            for (var i = 0; i < checkboxAll.length; i++) {
                checkboxAll[i].checked = status;
            }
        }

        // 正选考虑 全选按钮的选择,若多选中有任意一个影响则会改变全选选择;\
        for (var i = 0; i < checkboxAll.length; i++) {
            checkboxAll[i].onclick = function () {
                var nowStatus = this.checked;
                if (nowStatus) {
                    checkitem();
                } else {
                    checkAllBtn.checked = false;
                }
            }
        }

        // 反选
        reverseBtn.onclick = function () {
            for (var i = 0; i < checkboxAll.length; i++) {
                checkboxAll[i].checked = !checkboxAll[i].checked;

            }
            checkitem();

        }
        function checkitem() {
            var flag = true;
            for (var j = 0; j < checkboxAll.length; j++) {
                if (!checkboxAll[j].checked) {
                    flag = false;
                    break;
                }
            }
            checkAllBtn.checked = flag;
        }

    </script>
</body>

</html>